Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
Node | Promise not finishing

I am trying to fetch data of different collections from MongoDB. I do this with Node.js and promises. Here is some basic code:

await Promise.all(
        ["a", "b", "c"].map(async (collection) => {
            const query: any = { "_id": { $in: ids} }
            // I just use toArray for demonstration purposes
            const data = await this.db!.collection(collection).find(query).toArray()
            for (let i = 0; i < data.length; i++) {
                const document = data[i]
                // Do something...
            }
            console.log(collection)
            return true
        })
    )
 console.log("done")

I do this for eight collections (a, b, ..., h). The data gets fetched from the database and processed correctly in an acceptable amount of time. Then it prints the name for each collection. But it doesn't continue. It doesn't finish the promise and go to the done log.

The method gets called in a JS-Worker task. What could be the problem here? I never had problems with promises and bigger amount of data yet.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is actually a synchronous execution. It will not go to the next collection until the previous db call is finished. The arrow function should return a promise instead.

The solution is to rearrange the code in this way-

async function callDb(collection) {
    const query: any = { "_id": { $in: ids} }
    // I just use toArray for demonstration purposes
    const data = await this.db!.collection(collection).find(query).toArray()

    for (let i = 0; i < data.length; i++) {
        const document = data[i]
        // Do something...
    }
    console.log(collection)
    return true
}

await Promise.all(
    ["a", "b", "c"].map(callDb)
)

console.log("done")
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!